package com.cci.kangdao.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.MapUtils;
import org.apache.log4j.Logger;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeEntity;
import com.cci.kangdao.dao.ThreeServiceStationDao;
import com.cci.kangdao.service.ThreeServiceStationService;
import com.cci.kangdao.utilTool.GetDistance;
import com.cci.kangdao.utilTool.ParameterTool;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;




@Service("threeServiceStationService")
public class ThreeServiceStationImpl implements ThreeServiceStationService{

	private Logger log = Logger.getLogger(this.getClass().getName());
	@Autowired
	private ThreeServiceStationDao threeServiceStationDao;

	//DCEC用户报单获取附近服务站列表
	public ModelAndView getThreeServiceStation(Map<String, Object> map) {
		
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		/**
		 * 获取用户的经度纬度
		 */
		//用户经度
		String userPositionLon = MapUtils.getString(map,"positionLon");
		//用户纬度
		String userPositionLat = MapUtils.getString(map,"positionLat");
		//用户经纬度
		String endLonLat=userPositionLon+","+userPositionLat;
		
		String channalName = MapUtils.getString(map,"channalName");
		
		String ESN = MapUtils.getString(map,"ESN");
		Double Lat = MapUtils.getDouble(map, "positionLat");
		Double Lon = MapUtils.getDouble(map, "positionLon");
		String address = MapUtils.getString(map,"address");
		
		Map<String, Object> newmap = new HashMap<String, Object>();
		newmap.put("ESN", ESN);
		newmap.put("positionLat", Lat);
		newmap.put("positionLon", Lon);
		newmap.put("address", address);
		
		
		//调用crm接口返回服务站编号和企业id
		try {
			CRMResponeEntity cRMResponeEntity = CRMApiUtils.getCRMServiceApi().getRecommendedServiceStations(channalName,newmap);
			if(cRMResponeEntity.getStatus()!=0) {
				JSONObject obj = new JSONObject();
				if (cRMResponeEntity.getMessage() != null && cRMResponeEntity.getMessage().length() > 0){
					obj = new JSONObject();
					obj.put("status", 222);
					obj.put("msg",cRMResponeEntity.getMessage());
					obj.put("data", "");
				}else
				{
					obj.put("status", 222);
					obj.put("msg","crm获取信息失败");
					obj.put("data", "");
				}
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				return null;
			}else{
				JSONObject data = cRMResponeEntity.getData();
				try {
					//获取CRM返回的所有服务站详情
					JSONArray jsonArray = data.getJSONArray("stationInfos");   
					System.out.println(jsonArray);
					List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();  //保存给前端的数据，下面有进行转换
					List<Map<String,Object>> threeServiceStation;
					for(int i=0;i<jsonArray.size();i++){
						JSONObject object = jsonArray.getJSONObject(i);
						map.put("stationNo", object.get("stationNo"));
						map.put("channelId", object.get("serviceChannel"));
						//根据crm返回的服务站编号和企业id查询服务站信息
						threeServiceStation = threeServiceStationDao.getThreeServiceStation(map);
						if(threeServiceStation!=null){
							for(Map<String,Object> m:threeServiceStation){
								Map<String, Object> map2 = new HashMap<String, Object>();
								//服务站经度
								String positionLon = MapUtils.getString(m,"PositionLon");
								//服务站纬度
								String positionLat = MapUtils.getString(m,"PositionLat");
								String startLonLat = positionLon+","+positionLat;  //拼接服务站经纬度，得到开始地点
								Double distance = GetDistance.getDistance(startLonLat, endLonLat);  //算出用户和服务站之间的距离
								
								
								int ss = MapUtils.getIntValue(m,"SSType"); 
								int ssl = MapUtils.getIntValue(m,"SSLevel");
								map.put("ss", ss);
								map.put("ssl", ssl);
								Map<String, Object> ssType = threeServiceStationDao.getSSType(map);
								Map<String, Object> ssLevel = threeServiceStationDao.getSSLevel(map);
								map2.put("ID", m.get("ID"));
								map2.put("StationName", m.get("StationName"));
								map2.put("Telephone", m.get("Telephone"));
								map2.put("Address", m.get("Address"));
								map2.put("PositionLon", m.get("PositionLon"));
								map2.put("PositionLat", m.get("PositionLat"));
								if (ssType != null){
									map2.put("SSType", ssType.get("DValue"));
								}else
								{
									map2.put("SSType", "维护保养");
								}
								if (ssLevel != null){
									map2.put("SSLevel", ssLevel.get("DValue"));
								}else
								{
									map2.put("SSLevel", "其他");
								}
								map2.put("distance", distance+"km");
								
								list.add(map2);
							}
						}
						
						System.out.println("stationNo:"+object.get("stationNo"));
					}
					//转换JSON数据返给前端
					JSONObject obj = new JSONObject();
					JSONObject object = new JSONObject();
					JSONArray jsonArr = new JSONArray();
					
					JSONObject content;
					if(list!=null){
						for(Map<String,Object> cerT:list){
							content =new JSONObject();
							JSONArray SSLevel = new JSONArray();
							JSONArray SSType = new JSONArray();
							content.put("serviceStationId", cerT.get("ID"));
							content.put("serviceSite", cerT.get("StationName"));
							content.put("telephone", cerT.get("Telephone"));
							content.put("address", cerT.get("Address"));
							content.put("longitude", cerT.get("PositionLon"));
							content.put("latitude", cerT.get("PositionLat"));
							if("".equals(cerT.get("SSLevel"))||cerT.get("SSLevel")==null){
								content.put("SSLevel",SSLevel);
							}else{
								SSLevel.add( cerT.get("SSLevel"));
								content.put("SSLevel",SSLevel);
							}
							if("".equals(cerT.get("SSType"))||cerT.get("SSType")==null){
								content.put("SSType",SSType);
							}else{
								SSType.add( cerT.get("SSType"));
								content.put("SSType",SSType);
							}
							content.put("distance", cerT.get("distance"));
							jsonArr.add(content);
						}
					}
					object.put("threeServiceStationList", jsonArr);
					obj.put("status", 0);
					obj.put("msg", "");
					obj.put("data", object);
					ParameterTool.writeResponse(response, obj.toString());	
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage());
		}
		return null;
	}

}
